/*
Title:                  IV functions
Project:                Medellin Gang Governance
Authors:                Zach
Date Created:           Sept 27, 2019
Description:            This .do file provides a function used in the analysis code
*/
********************************************************************************
* Define the analysis function ************************************************
********************************************************************************
cap program drop multivar_reg
program define multivar_reg
    set matsize 10000

    syntax  [if], outcomevar(varlist) controls(varlist) specnames(string) filename(name) [cluster(varname) fixedeffects(varlist) standarized stars SUPRAHeader(string) SUPRACount(numlist)]

    if "`fixedeffects'"!="" local labsorb a(`fixedeffects')
    if "`fixedeffects'"=="" local labsorb noa

    if "`cluster'"!="" local lvce vce(cluster `cluster')
    if "`cluster'"=="" local lvce vce(r)

    local T = `:word count `controls''
    local O = `:word count `outcomevar'' * 3
    local P = `:word count `outcomevar'' + 1
    local labcontrols  `controls'


    ****************************************************************************
    * Make a matrix of the results *********************************************
    ****************************************************************************
    mat resultsMV = J(`T',`O', .)
    mat summaryMV = J(`T',3,.)
    mat NMV       = J(1,`P',.)

    if "`stars'"!="" mat stars = J(`T',`O'+3,0)

    local j = 1
    local p = 1
    local c = 1

    if "`standarized'"!=""{
      local std_controls
       foreach control in `controls' {
          tempvar `control'`j'
          egen ``control'`j'' = std(`control')
          local std_controls `std_controls' ``control'`c''
       }
       local controls
       local controls `std_controls'
    }

     foreach outcome of varlist `outcomevar'{

    if "`standarized'"!=""{
     tempvar `outcome'`j'
     egen ``outcome'`j'' = std(`outcome')
     local outcome ``outcome'`j''
    }

    qui reghdfe `outcome' `controls' `if', `labsorb' `lvce'

    mat NMV[1,`p'+1] = `e(N)'

    local i = 1
    foreach control in `controls' {

        mat resultsMV[`i',`j' ] = _b[`control']
        mat resultsMV[`i',`j' +1] = _se[`control']
        mat resultsMV[`i',`j' +2] = (2 * ttail(e(df_r), abs(_b[`control']/_se[`control'])))

        if "`stars'"!=""{
           mat stars[`i',`j'+3] = cond(resultsMV[`i',`j'+2] <= .01,3, ///
                                  cond(resultsMV[`i',`j'+2] <= .05,2, ///
                                  cond(resultsMV[`i',`j'+2] <= .1,1,0  ///
           )))
        }

        local ++i
    }

    local j = `j' + 3
    local ++p

    }

    local t = 1
    foreach control in `controls' {

        qui sum `control', d
        mat summaryMV[`t',1] = `r(mean)'
        mat summaryMV[`t',2] = `r(sd)'

        local ++t
    }

 mat resultsMV = summaryMV, resultsMV
    mat rownames resultsMV = `labcontrols'

cap drop N_var
 gen N_var=.
  label var N_var "\hline N"
    mat rownames NMV = N_var

* Define the number of specification specific elements
local title ""
local subtitle " "
local count = 1
forvalues num = 1/`:word count `outcomevar''  {
    local title `title' ,"\thead{Estimate \\ (SE) \\{} [p-value]}"
    local sub1 = `count'+1
    local subtitle `subtitle', "(`sub1')"
    local decimals 3
    local ++count
}

*** These loops assign the headers and titles
local header ""
foreach spec in `specnames' {
    local header `"`header', "\thead{`spec'}""'
}

if "`supracount'"!=""{
local space  `"" ""'
local spaces = floor(`:word count `outcomevar'' /`supracount' - 2)

local supraspace `"`space'"'

if `spaces'>1{
forvalue spaceloop=1/`spaces'{
local supraspace `" `supraspace' , `space' "'
}
}

local headercount=0
local multicolum 1,3,`= floor(`:word count `outcomevar'' / `supracount') '

foreach head in `supraheader' {
   local ++headercount

   if `headercount'==1  local multiheader `" "\uline{\hfill `head' \hfill}", `supraspace' "'
   if `headercount'>1 {
                      local multiheader `" `multiheader', "\uline{\hfill `head' \hfill}", `supraspace' "'
                      local multicolum   `multicolum';1,`=3 +(`headercount'-1)*`= floor(`:word count `outcomevar''  / `supracount')'',`= floor(`:word count `outcomevar''  / `supracount')'
}
}
local multiheader `" "", "", `multiheader' "'
local multicolum  `"multicol(`multicolum')"'

    if mod(`:word count `outcomevar'',`supracount') != 0 {
       forvalue m=1/`=mod(`:word count `outcomevar'',`supracount')'{
         local multiheader `"  `multiheader', " " "'
       }
    }

   local multiheader `"  `multiheader' \ "'

}

     * Format table and output.
qui frmttable, statmat(resultsMV) sdec(3)
qui frmttable, statmat(resultsMV) substat(2)

if "`stars'"!="" qui frmttable, statmat(resultsMV) varlabels sdec(`decimals') substat(2) annotate(stars) asymbol(*,**,***)
if "`stars'"=="" qui frmttable, statmat(resultsMV) varlabels sdec(`decimals') substat(2)
 qui frmttable, statmat(NMV) varlabel sdec(0) append

frmttable using outfiles/tables/`filename', ///
ctitle(`multiheader'  "", " " ,`header' \ "", "\thead{Sample Mean \\ (SD)}", `title' \ "","(1)",`subtitle') ///
tex fragment replace nocenter squarebrack ///
`multicolum'


end




********************************************************************************
***  *************************************************************************
********************************************************************************





cap program drop multivar_reg_mat
program define multivar_reg_mat
    set matsize 10000

    syntax  [if], outcomevar(varlist) controls(varlist) matname(name) [cluster(varname) fixedeffects(varlist) standarized ]

    if "`fixedeffects'"!="" local labsorb a(`fixedeffects')
    if "`fixedeffects'"=="" local labsorb noa

    if "`cluster'"!="" local lvce vce(cluster `cluster')
    if "`cluster'"=="" local lvce vce(r)

    local T = `:word count `controls''
    local labcontrols  `controls'


    ****************************************************************************
    * Make a matrix of the results *********************************************
    ****************************************************************************
    mat resultsMV = J(`T',3, .)
    mat sumMV     = J(`T',2,.)
    mat statsMV   = J(6,1,.)

    local j = 1
    local c = 1

     qui sum `outcomevar' `if', d
     mat statsMV[6,1] = `r(mean)'


    if "`standarized'"==""  local outcome `outcomevar'
    if "`standarized'"!=""{
      local std_controls
       foreach control in `controls' {
          tempvar `control'`j'
          egen ``control'`j'' = std(`control')
          local std_controls `std_controls' ``control'`j''
       }
       local controls `std_controls'

     tempvar `outcomevar'std
     egen ``outcomevar'std' = std(`outcomevar')
     local outcome ``outcomevar'std'
    }

    qui reghdfe `outcome' `controls' `if', `labsorb' `lvce'

   tempvar sample
   gen `sample'= e(sample)

   mat statsMV[1,1] = `e(N)'
   if "`cluster'"!="" mat statsMV[2,1] = `e(N_clust)'
   mat statsMV[3,1] = `e(r2_a)'
   mat statsMV[4,1] = `e(ll)'
   mat statsMV[5,1] = `e(F)'
       mat rownames statsMV = N N_clust r2_a ll F dvmean

  // scalar N = `e(N)'

    local i = 1
    foreach control in `controls' {

        mat resultsMV[`i',1] = _b[`control']
        mat resultsMV[`i',2] = _se[`control']
        mat resultsMV[`i',3] = (2 * ttail(e(df_r), abs(_b[`control']/_se[`control'])))
            mat colnames resultsMV = beta se p-val

  local ++i
    }




 local i = 1
    foreach control of varlist `labcontrols' {

        qui sum `control' if `sample'==1, d
        mat sumMV[`i',1] = `r(mean)'
        mat sumMV[`i',2] = `r(sd)'

        local ++i
    }

    mat rownames resultsMV = `labcontrols'

     * Format table and output.
qui frmttable, statmat(resultsMV) varlabels sdec(3)

    global  `matname'fe  `fixedeffects'    //return
    global  `matname'se  `cluster'         //return
    matrix  `matname'sum = sumMV         //return
    matrix  `matname'    = resultsMV         //return
    matrix  `matname'sta = statsMV           // return
  //  scalar  `matname'N   = N                 //ereturn

end





********************************************************************************
***  *************************************************************************
********************************************************************************

cap program drop mv_reg_table
program define mv_reg_table
    set matsize 10000

    syntax  [if], resultsmat(namelist) rowvars(varlist) specnames(string) filename(name) ///
    [clusterind(varlist) clusterlab(string) feind(varlist) felab(string) omittedind(varlist) omittedlab(string) ///
    STATS(namelist) stars SUPRAHeader(string) SUPRACount(numlist) SUPRALenght(numlist) novalues(name)]

cap matrix drop nopvalmat
cap matrix drop nopvalstars
cap matrix drop A
cap matrix drop B

if "`novalues'"=="yes" local columnmult = 2
if "`novalues'"=="no" local pvalehead  \\{} [p-value]
if "`novalues'"=="no" local columnmult = 3

    local T = `:word count `rowvars''
    local O = `:word count `resultsmat'' * 3
    local S = `:word count `stats''

    ****************************************************************************
    * Make a matrix of the results *********************************************
    ****************************************************************************
    mat tableMV = J(`T',`O', .)
    mat sumMV   = J(`T',3,.)
   // mat NMV     = J(1,(`O'/3)+1,.)

    if "`stats'"!=""{
      mat statsMV = J(`S',(`O'/3)+1,.)
      mat rowname statsMV = `stats'
     }

    if "`stars'"!="" mat stars = J(`T',`O'+3,0)

    local j = 1
    local p = 1
    mat rownames tableMV = `rowvars'
    mat rownames sumMV = `rowvars'

  foreach mat in `resultsmat'{
    //  mat NMV[1,`p'+1] =  `mat'N

    if "`stats'"!=""{
     foreach s in `stats'{
       local statsin  = rownumb(matrix(statsMV),`"`s'"')
       local statsout = rownumb(matrix(`mat'sta),`"`s'"')
        mat statsMV[`statsin',`p'+1] = `mat'sta[`statsout',1]
     }
    }

      foreach r in `rowvars' {

       local rnumin  = rownumb(matrix(tableMV),`"`r'"')
       local rnumout = rownumb(matrix(`mat'),`"`r'"')


        if "`rnumout'"!="."{
          mat sumMV[`rnumin',1] = `mat'sum[`rnumout',1]
          mat sumMV[`rnumin',2] = `mat'sum[`rnumout',2]
        }

          mat tableMV[`rnumin',`j' ]   =  `mat'[`rnumout',1]
          mat tableMV[`rnumin',`j' +1] =  `mat'[`rnumout',2]
          mat tableMV[`rnumin',`j' +2] =  `mat'[`rnumout',3]

          if "`stars'"!=""{
             mat stars[`rnumin',`j'+3] = cond(tableMV[`rnumin',`j'+2] <= .01,3, ///
                                         cond(tableMV[`rnumin',`j'+2] <= .05,2, ///
                                         cond(tableMV[`rnumin',`j'+2] <= .1,1,0  ///
             )))
          }
      }
    local j = `j' + 3
    local ++p
  }

 mat tableMV = sumMV, tableMV
     mat rownames tableMV = `rowvars'

if "`stats'"!=""{
  local newrnstats
  local statsdec
  local statcount = 1
  foreach s in `stats'{
   cap drop `s'_statvar
    gen `s'_statvar=.

    if "`s'"=="N"       cap label var `s'_statvar "N"
      if "`s'"=="N"         local `s'desc = 0
    if "`s'"=="N_clust" cap label var `s'_statvar "# of Clusters"
      if "`s'"=="N_clust"   local `s'desc = 0
    if "`s'"=="r2_a"    cap label var `s'_statvar "Adjusted \$ R^{2} $"
      if "`s'"=="r2_a"      local `s'desc = 4
    if "`s'"=="ll"      cap label var `s'_statvar "Log Likelihood"
      if "`s'"=="ll"        local `s'desc = 2
    if "`s'"=="F"       cap label var `s'_statvar "F-stat"
      if "`s'"=="F"         local `s'desc = 4
    if "`s'"=="dvmean"  cap label var `s'_statvar "Dep. var. mean"
      if "`s'"=="dvmean"    local `s'desc = 3
   local  newrnstats `newrnstats' `s'_statvar
   if `statcount'==1 local  statsdec   `statsdec'   ``s'desc'
   if `statcount'>1  local  statsdec   `statsdec' \ ``s'desc'
   local ++statcount
  }
 mat rownames statsMV = `newrnstats'
}

* Define the number of specification specific elements
local title ""
local subtitle " "
local count = 1
forvalues num = 1/`:word count `resultsmat''  {
    local title `title' ,`"\thead{Estimate \\ (SE) `pvalehead'}"'
    local sub1 = `count'+1
    local subtitle `subtitle', "(`sub1')"
    local decimals 3
    local ++count
}

*** These loops assign the headers and titles
local header ""
foreach spec in `specnames' {
    local header `"`header', "\thead{`spec'}""'
}

if "`supracount'"!=""{
local space  `"" ""'
local spaces = floor(`:word count `resultsmat'' /`supracount' - 2)

local supraspace `"`space'"'

if `spaces'>1{
forvalue spaceloop=1/`spaces'{
local supraspace `" `supraspace' , `space' "'
}
}

local headercount=0
local multicolum 1,3,`supralenght'

foreach head in `supraheader' {
   local ++headercount

   if `headercount'==1  local multiheader `" "\uline{\hfill `head' \hfill}", `supraspace' "'
   if `headercount'>1 {
                      local multiheader `" `multiheader', "\uline{\hfill `head' \hfill}", `supraspace' "'
                      local multicolum   `multicolum';1,`=3 +(`headercount'-1)*`= floor(`:word count `resultsmat''  / `supracount')'',`supralenght'
}
}
local multiheader `" "", "", `multiheader' "'
local multicolum  `"multicol(`multicolum')"'

    if mod(`:word count `resultsmat'',`supracount') != 0 {
       forvalue m=1/`=mod(`:word count `resultsmat'',`supracount')'{
         local multiheader `"  `multiheader', " " "'
       }
    }

   local multiheader `"  `multiheader' \ "'

}

/**/
  if "`feind'"!=""{
       local feindrow
       foreach f in  `resultsmat'  {
         if `"`feind'"'==`"${`f'fe}"' local indicatorfe " \checkmark "
         if `"`feind'"'!=`"${`f'fe}"' local indicatorfe
         local feindrow `"`feindrow', "`indicatorfe'""'
       }
      local feindrow `" \ "`felab'" , "", `feindrow' "'
  }
  if "`feind'"=="" local feindrow


  if "`clusterind'"!=""{
       local clusterindrow
       foreach c in  `resultsmat'  {
         if `"`clusterind'"'==`"${`c'se}"' local indicatorcluster " \checkmark "
         if `"`clusterind'"'!=`"${`c'se}"' local indicatorcluster
         local clusterindrow `"`clusterindrow' , "`indicatorcluster'""'
       }

      local clusterindrow `" \ "`clusterlab'", "", `clusterindrow' "'

  }
  if "`clusterind'"=="" local clusterindrow


  if "`omittedind'"!=""{
       local omittedindrow
    foreach o in  `resultsmat'  {
       local ommittedcount = 0
         foreach v of varlist `omittedind'{
           if (regexm(`"`: rownames `o''"',`"`v'"')==1) local ommittedcount = `ommittedcount' + 1
           if (regexm(`"`: rownames `o''"',`"`v'"')==0) local ommittedcount = `ommittedcount'
         }
       if `ommittedcount' > 0 local indicatoromitted " \checkmark "
       if `ommittedcount'<= 0 local indicatoromitted
       local omittedindrow `"`omittedindrow' , "`indicatoromitted'""'
     }
      local omittedindrow `" \ "`omittedlab'", "", `omittedindrow' "'
  }
  if "`omittedind'"=="" local omittedindrow

 local addrow addrow("\hline" `omittedindrow' `feindrow' `clusterindrow' )
 if "`omittedindrow'" == "" & "`feindrow'" == "" & "`clusterindrow'" == "" local addrow



if "`novalues'"=="yes"{
forvalues num = 0/`:word count `resultsmat''  {
 matrix A = tableMV[1...,`=`num'*3+1' .. `=`num'*3+2']
 matrix nopvalmat = nullmat(nopvalmat), A

if "`stars'"!=""{
 matrix B = stars[1...,`=`num'*3+1' .. `=`num'*3+2']
 matrix nopvalstars = nullmat(nopvalstars), B
}
}
matrix tableMV = nopvalmat
if "`stars'"!="" matrix stars = nopvalstars
}

     * Format table and output.
qui frmttable, statmat(tableMV) sdec(3)
qui frmttable, statmat(tableMV) substat(`=`columnmult'-1')

if "`stars'"!="" qui frmttable, statmat(tableMV) varlabels sdec(`decimals') substat(`=`columnmult'-1') annotate(stars) asymbol(*,**,***) `addrow'
if "`stars'"=="" qui frmttable, statmat(tableMV) varlabels sdec(`decimals') substat(`=`columnmult'-1') `addrow'
if "`stats'"!="" qui frmttable, statmat(statsMV) varlabel sdec(`statsdec') append

frmttable using outfiles/tables/`filename', ///
ctitle(`multiheader'  "", " " ,`header' \ "", "\thead{Sample Mean \\ (SD)}", `title' \ "","(1)",`subtitle') ///
tex fragment replace nocenter squarebrack ///
`multicolum'

cap drop *_statvar

end







cap program drop mv_reg_table_nosum
program define mv_reg_table_nosum
    set matsize 10000

    syntax  [if], resultsmat(namelist) rowvars(varlist) specnames(string) filename(name) ///
    [clusterind(varlist) clusterlab(string) feind(varlist) felab(string) omittedind(varlist) omittedlab(string) ///
    STATS(namelist) stars SUPRAHeader(string) SUPRACount(numlist) SUPRALenght(numlist) novalues(name) remove_sum(string)]

cap matrix drop nopvalmat
cap matrix drop nopvalstars
cap matrix drop A
cap matrix drop B

if "`novalues'"=="yes" local columnmult = 2
if "`novalues'"=="no" local pvalehead  \\{} [p-value]
if "`novalues'"=="no" local columnmult = 3

    local T = `:word count `rowvars''
    local O = `:word count `resultsmat'' * 3
    local S = `:word count `stats''

    ****************************************************************************
    * Make a matrix of the results *********************************************
    ****************************************************************************
    mat tableMV = J(`T',`O', .)
    mat sumMV   = J(`T',3,.)
   // mat NMV     = J(1,(`O'/3)+1,.)

    if "`stats'"!=""{
      mat statsMV = J(`S',(`O'/3)+1,.)
      mat rowname statsMV = `stats'
     }

    if "`stars'"!=""   mat stars = J(`T',`O'+3,0)




    local j = 1
    local p = 1
    mat rownames tableMV = `rowvars'
    mat rownames sumMV = `rowvars'

  foreach mat in `resultsmat'{
    //  mat NMV[1,`p'+1] =  `mat'N

    if "`stats'"!=""{
     foreach s in `stats'{
       local statsin  = rownumb(matrix(statsMV),`"`s'"')
       local statsout = rownumb(matrix(`mat'sta),`"`s'"')
        mat statsMV[`statsin',`p'+1] = `mat'sta[`statsout',1]
     }
    }

      foreach r in `rowvars' {

       local rnumin  = rownumb(matrix(tableMV),`"`r'"')
       local rnumout = rownumb(matrix(`mat'),`"`r'"')


   if "`remove_sum'" != "yes" {
        if "`rnumout'"!="."   {
          mat sumMV[`rnumin',1] = `mat'sum[`rnumout',1]
          mat sumMV[`rnumin',2] = `mat'sum[`rnumout',2]
        }
        }
          mat tableMV[`rnumin',`j' ]   =  `mat'[`rnumout',1]
          mat tableMV[`rnumin',`j' +1] =  `mat'[`rnumout',2]
          mat tableMV[`rnumin',`j' +2] =  `mat'[`rnumout',3]

          if "`stars'"!=""{

             mat stars[`rnumin',`j'+3  ] = cond(tableMV[`rnumin',`j'+2] <= .01,3, ///
                                           cond(tableMV[`rnumin',`j'+2] <= .05,2, ///
                                           cond(tableMV[`rnumin',`j'+2] <= .1,1,0  ///
             )))
          }
      }
    local j = `j' + 3
    local ++p
  }


 mat tableMV = sumMV, tableMV
 mat rownames tableMV = `rowvars'


*matlist tableMV
*matlist stars

if "`remove_sum'" == "yes" mat tableMV   =  tableMV[1..., 4....]
if "`remove_sum'" == "yes" mat stars     =  stars[1..., 4....]

*matlist tableMV
*matlist stars



if "`stats'"!=""{
  local newrnstats
  local statsdec
  local statcount = 1
  foreach s in `stats'{
   cap drop `s'_statvar
    gen `s'_statvar=.

    if "`s'"=="N"       cap label var `s'_statvar "N"
      if "`s'"=="N"         local `s'desc = 0
    if "`s'"=="N_clust" cap label var `s'_statvar "# of Clusters"
      if "`s'"=="N_clust"   local `s'desc = 0
    if "`s'"=="r2_a"    cap label var `s'_statvar "Adjusted \$ R^{2} $"
      if "`s'"=="r2_a"      local `s'desc = 4
    if "`s'"=="ll"      cap label var `s'_statvar "Log Likelihood"
      if "`s'"=="ll"        local `s'desc = 2
    if "`s'"=="F"       cap label var `s'_statvar "F-stat"
      if "`s'"=="F"         local `s'desc = 4
    if "`s'"=="dvmean"  cap label var `s'_statvar "Dep. var. mean"
      if "`s'"=="dvmean"    local `s'desc = 3
   local  newrnstats `newrnstats' `s'_statvar
   if `statcount'==1 local  statsdec   `statsdec'   ``s'desc'
   if `statcount'>1  local  statsdec   `statsdec' \ ``s'desc'
   local ++statcount
  }
 mat rownames statsMV = `newrnstats'
}

* Define the number of specification specific elements
local title ""
local subtitle " "

if "`remove_sum'" != "yes" local count = 1
if "`remove_sum'" == "yes" local count = 0



forvalues num = 1/`:word count `resultsmat''  {
    local title `title' ,`"\thead{Estimate \\ (SE) `pvalehead'}"'
    local sub1 = `count'+1
    local subtitle `subtitle', "(`sub1')"
    local decimals 3
    local ++count
}

*** These loops assign the headers and titles
local header ""
foreach spec in `specnames' {
    local header `"`header', "\thead{`spec'}""'
}

if "`supracount'"!=""{
local space  `"" ""'
local spaces = floor(`:word count `resultsmat'' /`supracount' - 2)

local supraspace `"`space'"'

if `spaces'>1{
forvalue spaceloop=1/`spaces'{
local supraspace `" `supraspace' , `space' "'
}
}

local headercount=0


if "`remove_sum'" == "yes" local multicol_remove_sum_index 2
if "`remove_sum'" != "yes" local multicol_remove_sum_index 3

local multicolum 1,`multicol_remove_sum_index',`supralenght'


foreach head in `supraheader' {
   local ++headercount

   if `headercount'==1  local multiheader `" "\uline{\hfill `head' \hfill}", `supraspace' "'
   if `headercount'>1 {
                      local multiheader `" `multiheader', "\uline{\hfill `head' \hfill}", `supraspace' "'
                      local multicolum   `multicolum';1,`=`multicol_remove_sum_index' +(`headercount'-1)*`= floor(`:word count `resultsmat''  / `supracount')'',`supralenght'
 }
}



if "`remove_sum'" != "yes" local multiheader_space_samplemean  "",

local multiheader `" "", `multiheader_space_samplemean' `multiheader' "'
local multicolum  `"multicol(`multicolum')"'

    if mod(`:word count `resultsmat'',`supracount') != 0 {
       forvalue m=1/`=mod(`:word count `resultsmat'',`supracount')'{
         local multiheader `"  `multiheader', " " "'
       }
    }

   local multiheader `"  `multiheader' \ "'

}

/**/
  if "`feind'"!=""{
       local feindrow
       foreach f in  `resultsmat'  {
         if `"`feind'"'==`"${`f'fe}"' local indicatorfe " \checkmark "
         if `"`feind'"'!=`"${`f'fe}"' local indicatorfe
         local feindrow `"`feindrow', "`indicatorfe'""'
       }
      local feindrow `" \ "`felab'" , "", `feindrow' "'
  }
  if "`feind'"=="" local feindrow


  if "`clusterind'"!=""{
       local clusterindrow
       foreach c in  `resultsmat'  {
         if `"`clusterind'"'==`"${`c'se}"' local indicatorcluster " \checkmark "
         if `"`clusterind'"'!=`"${`c'se}"' local indicatorcluster
         local clusterindrow `"`clusterindrow' , "`indicatorcluster'""'
       }

      local clusterindrow `" \ "`clusterlab'", "", `clusterindrow' "'

  }
  if "`clusterind'"=="" local clusterindrow


  if "`omittedind'"!=""{
       local omittedindrow
    foreach o in  `resultsmat'  {
       local ommittedcount = 0
         foreach v of varlist `omittedind'{
           if (regexm(`"`: rownames `o''"',`"`v'"')==1) local ommittedcount = `ommittedcount' + 1
           if (regexm(`"`: rownames `o''"',`"`v'"')==0) local ommittedcount = `ommittedcount'
         }
       if `ommittedcount' > 0 local indicatoromitted " \checkmark "
       if `ommittedcount'<= 0 local indicatoromitted
       local omittedindrow `"`omittedindrow' , "`indicatoromitted'""'
     }
      local omittedindrow `" \ "`omittedlab'", "", `omittedindrow' "'
  }
  if "`omittedind'"=="" local omittedindrow

 local addrow addrow("\hline" `omittedindrow' `feindrow' `clusterindrow' )

*di "`omittedindrow'"
*di "`feindrow'"
*di "`clusterindrow'"
if "`omittedindrow'" == "" & "`feindrow'" == "" & "`clusterindrow'" == "" local addrow



if "`novalues'"=="yes"{

if "`remove_sum'" == "yes" local adjust_pval_remove_sum = 1
if "`remove_sum'" != "yes" local adjust_pval_remove_sum = 0

local max_num = `:word count `resultsmat'' - `adjust_pval_remove_sum'
di "`max_num'"


forvalues num = 0/`max_num' {
 matrix A = tableMV[1...,`=`num'*3+1' .. `=`num'*3+2']
 matrix nopvalmat = nullmat(nopvalmat), A

if "`stars'"!=""{
 matrix B = stars[1...,`=`num'*3+1' .. `=`num'*3+2']
 matrix nopvalstars = nullmat(nopvalstars), B
                }
}

matrix tableMV = nopvalmat
if "`stars'"!="" matrix stars = nopvalstars
}

     * Format table and output.
qui frmttable, statmat(tableMV) sdec(3)
qui frmttable, statmat(tableMV) substat(`=`columnmult'-1')

if "`stars'"!="" qui frmttable, statmat(tableMV) varlabels sdec(`decimals') substat(`=`columnmult'-1') annotate(stars) asymbol(*,**,***) `addrow'
if "`stars'"=="" qui frmttable, statmat(tableMV) varlabels sdec(`decimals') substat(`=`columnmult'-1') `addrow'
if "`stats'"!="" qui frmttable, statmat(statsMV) varlabel sdec(`statsdec') append


   if "`remove_sum'" != "yes" {
                                        local header_space_samplemean         `"   " ",  "'
                                        local title_samplemean                `"   "\thead{Sample Mean \\ (SD)}" ,  "'
                                        local samplemean_number               `"   "(1)" ,   "'
    }


frmttable using outfiles/tables/`filename', ///
ctitle(`multiheader'  "", `header_space_samplemean' `header' \ "", `title_samplemean' `title' \ "", `samplemean_number' `subtitle') ///
tex fragment replace nocenter squarebrack ///
`multicolum'

cap drop *_statvar

end
